
import os
import time
from src import common, enums
from utils.initApp import mysql


class FilesService:
    def __init__(self, describe):
        self.file_describe = describe
        return

    def __add_file(self, values):
        _result = mysql.get('files', values, cur_key='id')
        if _result:
            return False
        else:
            mysql.insert('files', values)
            return True

    def __construct_user_path(self, values):
        user_id = values["userId"]
        upload_path = os.getcwd() + "/uploadFiles/"
        user_path = upload_path + user_id
        if not os.path.exists(user_path):
            os.makedirs(user_path)
        return user_path

    def __construct_cache_path(self, values):
        user_path = self.__construct_user_path(values)
        file_flag = values['flag']
        file_type = values['type']
        cache_name = "%s.%s.uploading" % (file_flag, file_type)
        path = os.path.join(user_path, cache_name)
        return path

    def __calc_table(self, values):
        table = values["table"]
        index = int(values["index"])

        _table = list(table)
        _table[index] = '1'
        _table = "".join(_table)
        return _table

    def __write_chunk(self, file, values):
        path = self.__construct_cache_path(values)
        index = int(values["index"])
        chunk_size = int(values["index"])
        table = values["table"]
        done = table.count("0") == 1 and table.find("0") == index
        offset = chunk_size * index

        chunk = open(path, 'ab+')
        chunk.seek(offset)
        chunk.write(file.stream.read())
        chunk.close()
        return done

    def __rename_chunk(self, values):
        cache_path = self.__construct_cache_path(values)
        old_name = os.path.splitext(cache_path)
        os.rename(cache_path, old_name[0])
        return old_name[0]

    def __download_piece(self, values):
        record = mysql.get('files', values, "id")
        size = int(record["size"])
        location = record["location"]
        ranges = values["ranges"]
        start = int(ranges['start']) if ranges['start'] else 0
        start = 0 if start < 0 else start
        end = int(ranges['end']) if ranges['end'] else size
        end = size if end > size else end

        file = open(location, 'rb')
        file.seek(start)
        piece = file.read(end - start + 1)
        file.close()

        result = dict()
        result['name'] = record["name"]
        result['start'] = start
        result['end'] = end
        result['size'] = size
        result["piece"] = piece
        # time.sleep(3)
        return result

    def __download_whole(self, values):
        result = mysql.get('files', values, "id")
        result["start"] = "0"
        result["end"] = result["size"]
        return result

    def upload(self, file, values):
        table = self.__calc_table(values)
        done = self.__write_chunk(file, values)

        if done:
            record = dict()
            record["userId"] = values["userId"]
            record["id"] = common.create_id()
            record["name"] = values["name"]
            record["parentId"] = values["parentId"]
            record["type"] = values["type"]
            record["size"] = values["size"]
            record["location"] = self.__rename_chunk(values)
            self.__add_file(record)

        result = dict()
        result["index"] = int(values["index"])
        result['flag'] = values["flag"]
        result['table'] = table

        print(result)
        # time.sleep()
        return result

    def download(self, values):
        if(values["ranges"]):
            print('断点下载模式')
            result = self.__download_piece(values)
            return result, 206
        else:
            print('普通下载模式')
            result = self.__download_whole(values)
            return result, 200

    def create(self, values):
        record = values
        result = self.__add_file(record)
        return result

    def list_all(self, values):
        parent_id = values['parentId'] or '-1'
        order = values['order'] or 'updateTime'
        sort = values['sort'] or 'asc'
        name = values['name'] or ''
        file_type = values['type'] or ''
        user_id = values['userId']

        sql = " SELECT * FROM files"
        sql += " WHERE parentId='{}' and userId='{}'".format(
            parent_id, user_id)
        sql += " and type ='{}'".format(file_type) if(file_type) else ''
        sql += " and name like '%{}%'".format(name) if(name) else ''
        sql += " order by {} {}".format(order, sort)

        result = mysql.customize_sql(sql)
        return result or []

    def rename(self, values):
        parent_id = values['parentId']
        name = values['name']
        file_id = values['id']
        sql = " SELECT * FROM files"
        sql += " WHERE parentId='{}' and name='{}' and not id='{}'".format(
            parent_id, name, file_id)
        record = mysql.customize_sql(sql)
        if not name:
            return {}, '名称不能为空', -1
        if record:
            return {}, '文件名已存在', -1
        else:
            result = mysql.update('files', values)
        return result, 'ok', 0

    def delete(self, values):
        mysql.multi_delete('share', values, filter_key="fileId")
        mysql.multi_delete('files', values)
        return {}

    def move(self, values):
        targetId = values['targetId']
        ids = values['ids'] + ['']
        sql = " UPDATE files set parentId='{}'".format(targetId)
        sql += ' WHERE id in {}'.format(tuple(ids))
        mysql.customize_sql(sql)
        return {}

    def detail(self, values):
        file_id = values['id']

        return {file_id}
